#!/usr/bin/python

import sys
import os
import time
import re

version_file_fmt = '''#ifndef VERSION_H_
#define VERSION_H_

#define VERSION_MAJOR {major}
#define VERSION       "{version}"
#define BUILD         "{build}"
#define CONFIG        "{config}"

#endif /* VERSION_H_ */
'''

filePath = sys.argv[1]
print("Generating: {}".format(filePath))

if len(sys.argv) > 2:
    config = sys.argv[2]
else:
    config = ""

cmd = "git describe --always --dirty"
output = os.popen(cmd)
describe = output.read()

match = re.match("v[0-9]+.", describe, re.I)
if match:
    major = int(match.group(0)[1:-1])
else:
    major = 0

lt = time.localtime()
if 'dirty' in describe:
	dirty = time.strftime("%Y%m%d%H%M", lt)
	version = describe.replace('dirty', dirty)
else:
	version = describe
version = version.replace('\n', '')

build = time.strftime("%Y-%m-%d %H:%M:%S", lt)

version_file_string = version_file_fmt.format(major=major, version=version, build=build, config=config)
print("version: {}\nbuild  : {}\nconfig : {}".format(version, build, config))
with open(filePath, 'w') as version_file:
    version_file.write(version_file_string)
